using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using DocumentCreationSystem.Models;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using WordDocument = DocumentFormat.OpenXml.Wordprocessing.Document;

namespace DocumentCreationSystem.Services
{
    /// <summary>
    /// 自动化章节创作服务
    /// 实现6500字章节、1000字分段、前三章回顾、自动保存等功能
    /// </summary>
    public class AutomatedChapterCreationService
    {
        private readonly ILogger<AutomatedChapterCreationService> _logger;
        private readonly IAIService _aiService;
        private readonly INovelCreationService _novelCreationService;
        private readonly IDocumentService _documentService;
        private readonly IFileNamingService _fileNamingService;
        private readonly EnhancedChapterContentService? _enhancedChapterContentService;
        private readonly TimelineService? _timelineService;
        private readonly CharacterUpdateService? _characterUpdateService;
        private readonly ChapterOutlineUpdateService? _chapterOutlineUpdateService;
        private readonly ContentQualityService? _contentQualityService;

        public AutomatedChapterCreationService(
            ILogger<AutomatedChapterCreationService> logger,
            IAIService aiService,
            INovelCreationService novelCreationService,
            IDocumentService documentService,
            IFileNamingService fileNamingService,
            EnhancedChapterContentService? enhancedChapterContentService = null,
            TimelineService? timelineService = null,
            CharacterUpdateService? characterUpdateService = null,
            ChapterOutlineUpdateService? chapterOutlineUpdateService = null,
            ContentQualityService? contentQualityService = null)
        {
            _logger = logger;
            _aiService = aiService;
            _novelCreationService = novelCreationService;
            _documentService = documentService;
            _fileNamingService = fileNamingService;
            _enhancedChapterContentService = enhancedChapterContentService;
            _timelineService = timelineService;
            _characterUpdateService = characterUpdateService;
            _chapterOutlineUpdateService = chapterOutlineUpdateService;
            _contentQualityService = contentQualityService;
        }

        /// <summary>
        /// 自动创作章节，支持分段创作和智能管理
        /// </summary>
        public async Task<ChapterCreationResult> CreateChapterAutomaticallyAsync(
            ChapterCreationRequest request,
            IProgress<ChapterCreationProgress>? progressCallback = null,
            CancellationToken cancellationToken = default)
        {
            var startTime = DateTime.Now;
            var result = new ChapterCreationResult();

            try
            {
                _logger.LogInformation($"开始自动创作章节 {request.ChapterNumber}");

                // 第一步：准备上下文
                progressCallback?.Report(new ChapterCreationProgress
                {
                    ChapterId = request.ChapterId,
                    CurrentWordCount = 0,
                    TargetWordCount = request.TargetWordCount,
                    ProgressPercentage = 5,
                    CurrentPhase = "准备阶段",
                    Status = "正在分析前文内容..."
                });

                var context = await BuildChapterContextAsync(request);
                cancellationToken.ThrowIfCancellationRequested();

                // 第二步：生成章节细纲
                progressCallback?.Report(new ChapterCreationProgress
                {
                    ChapterId = request.ChapterId,
                    CurrentWordCount = 0,
                    TargetWordCount = request.TargetWordCount,
                    ProgressPercentage = 15,
                    CurrentPhase = "规划阶段",
                    Status = "正在生成章节细纲..."
                });

                var detailedOutline = await GenerateDetailedChapterOutlineAsync(request, context);
                cancellationToken.ThrowIfCancellationRequested();

                // 从细纲中提取章节标题并更新请求
                var extractedTitle = ExtractChapterTitleFromOutline(detailedOutline, request.ChapterNumber);
                if (!string.IsNullOrEmpty(extractedTitle))
                {
                    request.ChapterTitle = extractedTitle;
                    _logger.LogInformation($"第{request.ChapterNumber}章标题已提取: {extractedTitle}");
                }

                // 保存章节细纲
                await SaveChapterOutlineAsync(request, detailedOutline);
                cancellationToken.ThrowIfCancellationRequested();

                // 第三步：生成章节内容（使用增强流程或分段创作）
                string chapterContent;
                if (_enhancedChapterContentService != null)
                {
                    // 使用增强章节内容服务
                    var enhancedRequest = new EnhancedChapterRequest
                    {
                        ProjectId = request.NovelProjectId,
                        ProjectPath = request.ProjectPath,
                        ChapterNumber = request.ChapterNumber,
                        ChapterOutline = detailedOutline,
                        TargetWordCount = request.TargetWordCount,
                        BookTitle = context.BookTitle,
                        CreativeDirection = context.CreativeDirection
                    };

                    var enhancedResult = await _enhancedChapterContentService.GenerateEnhancedChapterContentAsync(
                        enhancedRequest, cancellationToken);

                    if (enhancedResult.IsSuccess)
                    {
                        chapterContent = enhancedResult.Content;
                    }
                    else
                    {
                        // 回退到分段创作
                        chapterContent = await CreateChapterInSegmentsAsync(
                            request, detailedOutline, context, progressCallback, cancellationToken);
                    }
                }
                else
                {
                    // 使用原有的分段创作
                    chapterContent = await CreateChapterInSegmentsAsync(
                        request, detailedOutline, context, progressCallback, cancellationToken);
                }

                // 清理内容（移除output标签等）
                if (_contentQualityService != null)
                {
                    chapterContent = _contentQualityService.CleanOutputTags(chapterContent);
                }

                // 第四步：最终处理和保存
                progressCallback?.Report(new ChapterCreationProgress
                {
                    ChapterId = request.ChapterId,
                    CurrentWordCount = CountWords(chapterContent),
                    TargetWordCount = request.TargetWordCount,
                    ProgressPercentage = 95,
                    CurrentPhase = "完成阶段",
                    Status = "正在保存章节..."
                });

                await SaveChapterAsync(request, chapterContent);

                // 第五步：执行后处理流程
                await PostProcessChapterAsync(request, chapterContent);

                result.IsSuccess = true;
                result.Content = chapterContent;
                result.WordCount = CountWords(chapterContent);
                result.IsCompleted = true;
                result.CreationTime = DateTime.Now - startTime;

                progressCallback?.Report(new ChapterCreationProgress
                {
                    ChapterId = request.ChapterId,
                    CurrentWordCount = result.WordCount,
                    TargetWordCount = request.TargetWordCount,
                    ProgressPercentage = 100,
                    CurrentPhase = "完成",
                    Status = "章节创作完成"
                });

                _logger.LogInformation($"章节 {request.ChapterNumber} 创作完成，共 {result.WordCount} 字");
                return result;
            }
            catch (OperationCanceledException)
            {
                result.ErrorMessage = "创作已取消";
                result.CreationTime = DateTime.Now - startTime;
                _logger.LogInformation($"章节 {request.ChapterNumber} 创作已取消");
                return result;
            }
            catch (Exception ex)
            {
                result.ErrorMessage = ex.Message;
                result.CreationTime = DateTime.Now - startTime;
                _logger.LogError(ex, $"章节 {request.ChapterNumber} 创作失败");
                return result;
            }
        }

        /// <summary>
        /// 构建章节创作上下文
        /// </summary>
        private async Task<ChapterContext> BuildChapterContextAsync(ChapterCreationRequest request)
        {
            var context = new ChapterContext
            {
                ChapterNumber = request.ChapterNumber,
                BookTitle = request.BookTitle,
                OverallOutline = request.OverallOutline
            };

            // 获取前三章内容
            if (request.ChapterNumber > 1)
            {
                var startChapter = Math.Max(1, request.ChapterNumber - 3);
                context.PreviousChapters = await GetPreviousChaptersAsync(
                    request.NovelProjectId, startChapter, request.ChapterNumber - 1);
            }

            // 获取角色信息
            context.Characters = await GetCharacterInfoAsync(request.NovelProjectId);

            // 获取世界观设定
            context.WorldSettings = await GetWorldSettingsAsync(request.NovelProjectId);

            return context;
        }

        /// <summary>
        /// 生成详细的章节大纲
        /// </summary>
        private async Task<string> GenerateDetailedChapterOutlineAsync(
            ChapterCreationRequest request, ChapterContext context)
        {
            var prompt = BuildOutlinePrompt(request, context);
            return await _aiService.GenerateTextAsync(prompt, 2000, 0.8f);
        }

        /// <summary>
        /// 分段创作章节内容
        /// </summary>
        private async Task<string> CreateChapterInSegmentsAsync(
            ChapterCreationRequest request,
            string outline,
            ChapterContext context,
            IProgress<ChapterCreationProgress>? progressCallback,
            CancellationToken cancellationToken)
        {
            var totalContent = new StringBuilder();
            var currentWordCount = 0;
            var segmentNumber = 0;
            var segmentSize = request.SegmentWordCount;
            var targetWords = request.TargetWordCount;

            while (currentWordCount < targetWords)
            {
                cancellationToken.ThrowIfCancellationRequested();
                
                segmentNumber++;
                var remainingWords = Math.Min(segmentSize, targetWords - currentWordCount);
                var isLastSegment = currentWordCount + remainingWords >= targetWords;

                // 报告进度
                var progressPercentage = 15 + (int)(currentWordCount * 80.0 / targetWords);
                progressCallback?.Report(new ChapterCreationProgress
                {
                    ChapterId = request.ChapterId,
                    CurrentWordCount = currentWordCount,
                    TargetWordCount = targetWords,
                    ProgressPercentage = progressPercentage,
                    CurrentPhase = "创作阶段",
                    Status = $"正在创作第 {segmentNumber} 段 ({currentWordCount}/{targetWords} 字)"
                });

                // 生成段落内容
                var segmentContent = await GenerateSegmentContentAsync(
                    request, outline, context, totalContent.ToString(), remainingWords, isLastSegment);

                totalContent.AppendLine(segmentContent);
                currentWordCount = CountWords(totalContent.ToString());

                // 每完成一段就保存一次（避免丢失）
                if (segmentNumber % 2 == 0 || isLastSegment)
                {
                    await SaveTemporaryContentAsync(request.ChapterId, totalContent.ToString());
                }

                // 避免API限制
                await Task.Delay(1500, cancellationToken);

                // 如果接近目标字数，检查是否需要收尾
                if (currentWordCount >= targetWords - 500 && !isLastSegment)
                {
                    break;
                }
            }

            // 如果需要，生成收尾段落
            if (currentWordCount < targetWords - 200)
            {
                var endingContent = await GenerateChapterEndingAsync(
                    request, outline, context, totalContent.ToString());
                totalContent.AppendLine(endingContent);
            }

            return totalContent.ToString();
        }

        /// <summary>
        /// 生成段落内容
        /// </summary>
        private async Task<string> GenerateSegmentContentAsync(
            ChapterCreationRequest request,
            string outline,
            ChapterContext context,
            string currentContent,
            int targetWords,
            bool isLastSegment)
        {
            var prompt = BuildSegmentPrompt(request, outline, context, currentContent, targetWords, isLastSegment);
            return await _aiService.GenerateTextAsync(prompt, targetWords + 500, 0.9f);
        }

        /// <summary>
        /// 生成章节结尾
        /// </summary>
        private async Task<string> GenerateChapterEndingAsync(
            ChapterCreationRequest request,
            string outline,
            ChapterContext context,
            string currentContent)
        {
            var prompt = $@"请为以下章节内容生成一个合适的结尾：

章节大纲：
{outline}

当前章节内容：
{currentContent.Substring(Math.Max(0, currentContent.Length - 1000))}

要求：
1. 结尾要与前文自然衔接
2. 为下一章留下适当的悬念或过渡
3. 符合章节的整体节奏
4. 字数控制在200-500字
5. 体现章节的主要成就或转折

请生成章节结尾：";

            return await _aiService.GenerateTextAsync(prompt, 800, 0.8f);
        }

        /// <summary>
        /// 构建大纲生成提示词
        /// </summary>
        private string BuildOutlinePrompt(ChapterCreationRequest request, ChapterContext context)
        {
            var previousChapterInfo = "";
            if (context.PreviousChapters.Any())
            {
                previousChapterInfo = "前几章概要：\n";
                foreach (var chapter in context.PreviousChapters)
                {
                    previousChapterInfo += $"第{chapter.ChapterNumber}章：{chapter.Title}\n";
                    if (!string.IsNullOrEmpty(chapter.Summary))
                    {
                        previousChapterInfo += $"概要：{chapter.Summary}\n";
                    }
                }
                previousChapterInfo += "\n";
            }

            var characterInfo = "";
            if (context.Characters.Any())
            {
                characterInfo = "主要角色信息：\n";
                foreach (var character in context.Characters)
                {
                    characterInfo += $"- {character.Name}：{character.Description}\n";
                    if (character.Attributes.Any())
                    {
                        characterInfo += $"  属性：{string.Join(", ", character.Attributes.Select(a => $"{a.Key}={a.Value}"))}\n";
                    }
                    if (character.Skills.Any())
                    {
                        characterInfo += $"  技能：{string.Join(", ", character.Skills)}\n";
                    }
                }
                characterInfo += "\n";
            }

            var worldSettingInfo = "";
            if (!string.IsNullOrEmpty(context.WorldSettings))
            {
                worldSettingInfo = $"世界观设定：\n{context.WorldSettings}\n\n";
            }

            return $@"请为以下小说的第{request.ChapterNumber}章生成详细的章节细纲：

书籍信息：
- 标题：{context.BookTitle}
- 目标字数：{request.TargetWordCount}字

{worldSettingInfo}{characterInfo}{previousChapterInfo}全书大纲：
{context.OverallOutline}

**重要要求：**
1. 细纲必须严格依照全书大纲的设定和情节发展
2. 人物行为必须符合角色设定和当前状态
3. 情节发展必须与前文保持连贯性
4. 不得随意添加大纲中未提及的重要角色或情节
5. 必须推进主线剧情，不得偏离核心故事线

请按照以下格式生成第{request.ChapterNumber}章的详细细纲：

## 第{request.ChapterNumber}章：[章节标题]

### 场景设定
- 时间：[具体时间]
- 地点：[详细地点描述]
- 环境：[环境氛围和背景]
- 道具：[重要道具和物品]

### 人物安排
- 主要人物：[本章出场的主要角色及其状态]
- 次要人物：[配角和群众角色]
- 人物关系：[角色间的关系变化]
- 人物心理：[关键角色的心理状态]

### 主线发展
- 核心事件：[本章的核心情节]
- 爽点设计：[读者期待的精彩内容]
- 冲突点：[矛盾和冲突的爆发]
- 悬念设置：[留给读者的疑问和期待]

### 预期结果
- 情节推进：[对整体故事的推进作用]
- 角色成长：[角色的变化和成长]
- 伏笔铺设：[为后续章节埋下的伏笔]
- 章节结尾：[本章的结束方式和过渡]

请确保细纲详细具体，能够指导{request.TargetWordCount}字的标准小说正文创作。";
        }

        /// <summary>
        /// 构建段落生成提示词
        /// </summary>
        private string BuildSegmentPrompt(
            ChapterCreationRequest request,
            string outline,
            ChapterContext context,
            string currentContent,
            int targetWords,
            bool isLastSegment)
        {
            var contextInfo = "";
            if (!string.IsNullOrEmpty(currentContent))
            {
                var recentContent = currentContent.Length > 1000 
                    ? currentContent.Substring(currentContent.Length - 1000)
                    : currentContent;
                contextInfo = $"当前章节已写内容（最近1000字）：\n{recentContent}\n\n";
            }

            var endingInstruction = isLastSegment 
                ? "7. 这是本章的最后一段，请适当收尾并为下章做铺垫\n"
                : "";

            var continuityInstruction = string.IsNullOrEmpty(currentContent)
                ? "这是本章的开头部分。"
                : "请无缝衔接前文内容继续创作，不要添加任何解释说明。";

            return $@"请根据以下章节细纲创作标准小说正文：

章节细纲：
{outline}

{contextInfo}创作要求：
1. 目标字数：约{targetWords}字
2. 输出标准小说正文格式，不要包含任何解释、说明、总结等内容
3. {continuityInstruction}
4. 保持与前文的连贯性和一致性，无缝衔接
5. 情节发展自然流畅，严格按照细纲执行
6. 对话生动真实，符合角色性格设定
7. 描写细腻丰富，注重环境、动作、心理描写
8. 保持适当的节奏感和张力
{endingInstruction}
9. 只输出小说正文内容，不要输出任何其他文字

请开始创作小说正文：";
        }

        /// <summary>
        /// 获取前几章内容
        /// </summary>
        private async Task<List<ChapterSummary>> GetPreviousChaptersAsync(int novelProjectId, int startChapter, int endChapter)
        {
            // 这里需要实现从数据库获取前几章内容的逻辑
            // 暂时返回模拟数据
            var chapters = new List<ChapterSummary>();
            for (int i = startChapter; i <= endChapter; i++)
            {
                chapters.Add(new ChapterSummary
                {
                    ChapterNumber = i,
                    Title = $"第{i}章",
                    Summary = $"第{i}章的主要内容概要"
                });
            }
            return chapters;
        }

        /// <summary>
        /// 获取角色信息
        /// </summary>
        private async Task<List<CharacterInfo>> GetCharacterInfoAsync(int novelProjectId)
        {
            // 这里需要实现从数据库获取角色信息的逻辑
            // 暂时返回模拟数据
            return new List<CharacterInfo>
            {
                new CharacterInfo { Name = "主角", Description = "主要角色描述" }
            };
        }

        /// <summary>
        /// 获取世界观设定
        /// </summary>
        private async Task<string> GetWorldSettingsAsync(int novelProjectId)
        {
            // 这里需要实现从数据库获取世界观设定的逻辑
            // 暂时返回模拟数据
            return "世界观设定信息";
        }

        /// <summary>
        /// 保存章节细纲
        /// </summary>
        private async Task SaveChapterOutlineAsync(ChapterCreationRequest request, string outline)
        {
            try
            {
                if (string.IsNullOrEmpty(request.ProjectPath))
                    return;

                var outlinesPath = Path.Combine(request.ProjectPath, "大纲", "章节");
                if (!Directory.Exists(outlinesPath))
                {
                    Directory.CreateDirectory(outlinesPath);
                }

                var fileName = $"第{request.ChapterNumber:D3}章_细纲.txt";
                var filePath = Path.Combine(outlinesPath, fileName);

                await File.WriteAllTextAsync(filePath, outline);

                _logger.LogInformation($"章节细纲已保存: {filePath}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"保存章节细纲失败: 第{request.ChapterNumber}章");
            }
        }

        /// <summary>
        /// 保存临时内容
        /// </summary>
        private async Task SaveTemporaryContentAsync(int chapterId, string content)
        {
            // 这里需要实现保存临时内容的逻辑
            await Task.Delay(100); // 模拟保存操作
        }

        /// <summary>
        /// 保存章节
        /// </summary>
        private async Task SaveChapterAsync(ChapterCreationRequest request, string content)
        {
            // 保存到数据库
            // 这里需要实现保存到数据库的逻辑

            // 保存到文件
            if (request.AutoSave && !string.IsNullOrEmpty(request.ProjectPath))
            {
                await SaveChapterToFileAsync(request, content);
            }
        }

        /// <summary>
        /// 保存章节到文件
        /// </summary>
        private async Task SaveChapterToFileAsync(ChapterCreationRequest request, string content)
        {
            try
            {
                var fileName = GenerateChapterFileName(request);
                var chaptersPath = Path.Combine(request.ProjectPath, "章节");

                if (!Directory.Exists(chaptersPath))
                {
                    Directory.CreateDirectory(chaptersPath);
                }

                var fullPath = Path.Combine(chaptersPath, fileName);
                await CreateChapterDocxAsync(fullPath, request, content);

                _logger.LogInformation($"章节已保存到文件：{fullPath}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"保存章节到文件失败：{request.ChapterNumber}");
            }
        }

        /// <summary>
        /// 生成章节文件名
        /// 按照要求格式：书籍名称_第X卷_卷宗名称_第X章_章节名称
        /// </summary>
        private string GenerateChapterFileName(ChapterCreationRequest request)
        {
            // 使用文件命名服务生成标准化的文件名
            return _fileNamingService.GenerateChapterFileName(
                request.BookTitle,
                request.VolumeNumber,
                request.VolumeName ?? "",
                request.ChapterNumber,
                request.ChapterTitle ?? "",
                ".docx");
        }



        /// <summary>
        /// 创建章节docx文件
        /// </summary>
        private async Task CreateChapterDocxAsync(string filePath, ChapterCreationRequest request, string content)
        {
            await Task.Run(() =>
            {
                using var document = WordprocessingDocument.Create(filePath, WordprocessingDocumentType.Document);
                var mainPart = document.AddMainDocumentPart();
                mainPart.Document = new WordDocument();
                var body = mainPart.Document.AppendChild(new Body());

                // 添加标题
                var titleText = $"第{request.ChapterNumber}章";
                if (!string.IsNullOrEmpty(request.ChapterTitle))
                {
                    titleText += $" {request.ChapterTitle}";
                }

                var titleParagraph = new Paragraph();
                var titleRun = new Run();
                titleRun.AppendChild(new Text(titleText));
                titleParagraph.AppendChild(titleRun);
                body.AppendChild(titleParagraph);

                // 添加空行
                body.AppendChild(new Paragraph());

                // 添加内容
                var paragraphs = content.Split('\n', StringSplitOptions.None);
                foreach (var paragraphText in paragraphs)
                {
                    var paragraph = new Paragraph();
                    var run = new Run();
                    run.AppendChild(new Text(paragraphText));
                    paragraph.AppendChild(run);
                    body.AppendChild(paragraph);
                }
            });
        }

        /// <summary>
        /// 计算字数
        /// </summary>
        private int CountWords(string text)
        {
            if (string.IsNullOrWhiteSpace(text))
                return 0;

            var chineseCharCount = Regex.Matches(text, @"[\u4e00-\u9fa5]").Count;
            var englishWords = Regex.Matches(text, @"\b[a-zA-Z]+\b").Count;

            return chineseCharCount + englishWords;
        }

        /// <summary>
        /// 清理文件名中的非法字符
        /// </summary>
        private string SanitizeFileName(string fileName)
        {
            var invalidChars = Path.GetInvalidFileNameChars();
            var sanitized = fileName;

            foreach (var invalidChar in invalidChars)
            {
                sanitized = sanitized.Replace(invalidChar, '_');
            }

            // 替换一些常见的特殊字符
            sanitized = sanitized.Replace(":", "：")
                                 .Replace("?", "？")
                                 .Replace("*", "＊")
                                 .Replace("<", "＜")
                                 .Replace(">", "＞")
                                 .Replace("|", "｜")
                                 .Replace("\"", "\"")
                                 .Replace("/", "／")
                                 .Replace("\\", "＼");

            return sanitized.Trim();
        }

        /// <summary>
        /// 从章节细纲中提取章节标题
        /// </summary>
        private string ExtractChapterTitleFromOutline(string outline, int chapterNumber)
        {
            try
            {
                if (string.IsNullOrEmpty(outline))
                {
                    return $"第{chapterNumber}章";
                }

                // 查找章节标题的多种可能格式
                var patterns = new[]
                {
                    $@"##\s*第{chapterNumber}章[：:]\s*(.+?)(?:\n|$)",  // ## 第X章：标题
                    $@"第{chapterNumber}章[：:]\s*(.+?)(?:\n|$)",       // 第X章：标题
                    $@"##\s*第{chapterNumber}章\s+(.+?)(?:\n|$)",      // ## 第X章 标题
                    $@"第{chapterNumber}章\s+(.+?)(?:\n|$)"            // 第X章 标题
                };

                foreach (var pattern in patterns)
                {
                    var match = System.Text.RegularExpressions.Regex.Match(outline, pattern,
                        System.Text.RegularExpressions.RegexOptions.IgnoreCase |
                        System.Text.RegularExpressions.RegexOptions.Multiline);

                    if (match.Success && match.Groups.Count > 1)
                    {
                        var title = match.Groups[1].Value.Trim();

                        // 清理标题中的特殊字符和格式标记
                        title = title.Replace("[", "").Replace("]", "")
                                   .Replace("【", "").Replace("】", "")
                                   .Replace("（", "").Replace("）", "")
                                   .Replace("(", "").Replace(")", "")
                                   .Trim();

                        // 如果标题不为空且不是占位符，返回完整标题
                        if (!string.IsNullOrEmpty(title) &&
                            !title.Contains("章节标题") &&
                            !title.Contains("标题") &&
                            title.Length > 1)
                        {
                            return $"第{chapterNumber}章_{title}";
                        }
                    }
                }

                // 如果没有找到合适的标题，尝试从细纲内容中推断
                var contentTitle = InferTitleFromContent(outline, chapterNumber);
                if (!string.IsNullOrEmpty(contentTitle))
                {
                    return contentTitle;
                }

                // 默认返回章节号
                return $"第{chapterNumber}章";
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"提取第{chapterNumber}章标题失败");
                return $"第{chapterNumber}章";
            }
        }

        /// <summary>
        /// 从细纲内容中推断章节标题
        /// </summary>
        private string InferTitleFromContent(string outline, int chapterNumber)
        {
            try
            {
                // 查找核心事件或主要情节
                var coreEventMatch = System.Text.RegularExpressions.Regex.Match(outline,
                    @"核心事件[：:]\s*(.+?)(?:\n|$)",
                    System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                if (coreEventMatch.Success)
                {
                    var coreEvent = coreEventMatch.Groups[1].Value.Trim();
                    if (!string.IsNullOrEmpty(coreEvent) && coreEvent.Length <= 20)
                    {
                        return $"第{chapterNumber}章_{coreEvent}";
                    }
                }

                // 查找主要场景
                var sceneMatch = System.Text.RegularExpressions.Regex.Match(outline,
                    @"地点[：:]\s*(.+?)(?:\n|$)",
                    System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                if (sceneMatch.Success)
                {
                    var scene = sceneMatch.Groups[1].Value.Trim();
                    if (!string.IsNullOrEmpty(scene) && scene.Length <= 15)
                    {
                        return $"第{chapterNumber}章_{scene}";
                    }
                }

                return string.Empty;
            }
            catch
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// 章节完成后的后处理流程
        /// </summary>
        private async Task PostProcessChapterAsync(ChapterCreationRequest request, string chapterContent)
        {
            try
            {
                _logger.LogInformation($"开始执行第{request.ChapterNumber}章后处理流程");

                // 1. 更新时间线
                if (_timelineService != null)
                {
                    await _timelineService.UpdateChapterTimelineAsync(
                        request.NovelProjectId, request.ChapterNumber, chapterContent,
                        request.ChapterTitle ?? $"第{request.ChapterNumber}章");
                }

                // 2. 更新角色信息
                if (_characterUpdateService != null)
                {
                    await _characterUpdateService.UpdateCharactersAfterChapterAsync(
                        request.NovelProjectId, request.ChapterNumber, chapterContent,
                        request.ChapterTitle ?? $"第{request.ChapterNumber}章");
                }

                // 3. 更新后续章节细纲
                if (_chapterOutlineUpdateService != null)
                {
                    await _chapterOutlineUpdateService.UpdateSubsequentChapterOutlinesAsync(
                        request.NovelProjectId, request.ChapterNumber, chapterContent, 3);
                }

                _logger.LogInformation($"第{request.ChapterNumber}章后处理流程完成");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"第{request.ChapterNumber}章后处理流程失败");
                // 不抛出异常，避免影响主流程
            }
        }
    }

    /// <summary>
    /// 章节创作请求
    /// </summary>
    public class ChapterCreationRequest
    {
        public int ChapterId { get; set; }
        public int NovelProjectId { get; set; }
        public int ChapterNumber { get; set; }
        public string ChapterTitle { get; set; } = "";
        public string BookTitle { get; set; } = "";
        public string OverallOutline { get; set; } = "";
        public int TargetWordCount { get; set; } = 6500;
        public int SegmentWordCount { get; set; } = 1000;
        public int VolumeNumber { get; set; }
        public string VolumeName { get; set; } = "";
        public bool AutoSave { get; set; } = true;
        public string ProjectPath { get; set; } = "";
    }

    /// <summary>
    /// 章节创作上下文
    /// </summary>
    public class ChapterContext
    {
        public int ChapterNumber { get; set; }
        public string BookTitle { get; set; } = "";
        public string OverallOutline { get; set; } = "";
        public List<ChapterSummary> PreviousChapters { get; set; } = new();
        public List<CharacterInfo> Characters { get; set; } = new();
        public string WorldSettings { get; set; } = "";
        public int TargetWordCount { get; set; } = 6500;
        public string WritingStyle { get; set; } = "现代网络小说";
        public string CreativeDirection { get; set; } = "";
    }

    /// <summary>
    /// 章节概要
    /// </summary>
    public class ChapterSummary
    {
        public int ChapterNumber { get; set; }
        public string Title { get; set; } = "";
        public string Summary { get; set; } = "";
        public string Content { get; set; } = "";
    }


}
